﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace Savage.DotNetLibrary.ProtocolLibrary
{
    public class GZipWrapper
    {
        public static void Decompress(string sourcePath)
        { 
            Decompress(sourcePath, Path.GetDirectoryName(sourcePath) + @"\" + Path.GetFileNameWithoutExtension(sourcePath));
        }

        public static void Decompress(string sourcePath, string destinationFilePath)
        {
            using (FileStream sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (FileStream destinationStream = new FileStream(destinationFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                {
                    Decompress(sourceStream, destinationStream);
                }
            }
        }

        public static void Decompress(Stream source, Stream destination)
        {
            using (GZipStream input = new GZipStream(source, CompressionMode.Decompress))
            {
                Pump(input, destination);
            }
        }

        public static void Compress(string sourcePath)
        {
            Compress(sourcePath, sourcePath + ".gz");
        }

        public static void Compress(string sourcePath, string destinationFilePath)
        {
            using (FileStream sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (FileStream destinationStream = new FileStream(destinationFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                {
                    Compress(sourceStream, destinationStream);
                }
            }
        }

        public static void Compress(Stream source, Stream destination)
        {
            using (GZipStream output = new GZipStream(destination, CompressionMode.Compress))
            {
                Pump(source, output);
            }
        }

        private static void Pump(Stream input, Stream output)
        { 
            byte[] buffer = new byte[4096];
            int count;
            while ((count = input.Read(buffer, 0, buffer.Length)) != 0) 
            {
                output.Write(buffer, 0, count);
            }
        }
    }
}
